#!/usr/bin/env python

import smtplib
import os
import sqlite3
import cgi
import string
import random
import sys
import datetime

def hs_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))


def adminErrorMail(jobid, handshake):
    sender = 'jake.lin@uni.lu'
    receivers = []
    receivers.append("jlin212@gmail.com")
    message = """From: IDARE Metanode Server <thomas.pfau@uni.lu>
To: User
Subject: %s

%s
    """ %(jobid + "_UpdateError",  "\n\nFatal error invalid jobid_handshake " + jobid + "_" + handshake + " on web server update. Need to investigateGCMSJob results are posted. Use link below to access result files and cost summary.")

    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message)
    except SMTPException:
        print "Error: unable to send email"



conn = sqlite3.connect('/db/metanode.db')
cur = conn.cursor()
#cur.execute("DROP TABLE idare_jobs;")
#cur.execute("CREATE TABLE idare_jobs(name text, email text, org text, project text, imgformat text, handshake text, status text default 'new', jobid INTEGER PRIMARY KEY AUTOINCREMENT);")

qform = cgi.FieldStorage()
#jobid = "13"
jobid = qform.getvalue('jobID')
logfile = open('metanode.log', 'a')
logfile.write("started updating jobid " + jobid + " datetime " + datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") + "\n")
if (jobid == None):
    error = "key not provided"
    sys.exit()
#http://idare-server.uni.lu/cgi-bin/update_idare.cgi?jobID=11&hs=89D0E2&status=status
#status = "completed"
status = qform.getvalue('status')
#handshake = "GCUVKZ" 
handshake = qform.getvalue('hs')
if (handshake == 'CONNECTION'):
	#If we have a connectivity issue, inform the Admins, but don't inform the user.
	adminErrorMail(jobid,'Connection Error')
	logfile.close()
	conn.close()
	sys.exit()
	
cur.execute("select name, email, project from idare_jobs where jobid = " + jobid + " and handshake = '" + handshake + "'")
#name, email, org, handshake) VALUES('" + name + "','" + email + "','uta','" + hs +"');")
results = cur.fetchone()
if (results == None or len(results) == 0):
    error = "handshake/jobid invalid " + jobid

    logfile.write(error + " " + str(handshake) + " \n")
    print("no results for job, invalid handshake/jobid, fatal error, send admin email")
    adminErrorMail(jobid, handshake)
    conn.close()
    logfile.close()
    sys.exit()
    #write error to job folder and exit

if (status == "SUCCESS"):
    os.system("ln -s /db/jobs/_" + jobid + "/output/IDARENodes.zip /var/www/metanodeui/data/" + handshake + ".zip")

email = results[1]
name = results[0]
project = results[2]
#cur.execute("INSERT INTO idare_jobs (name, email, org, handshake) VALUES('" + name + "','" + email + "','uta','" + hs +"');")
#lid = cur.lastrowid
#print "The last Id of the inserted row is %d" % lid
#print ("name " + name + " email " + email)

#symlink to uploaded results, by pass check if they exists upon handshake
"""
os.system('mkdir /db/jobs/_' + str(lid))
os.system('chmod 777 /db/jobs/_' + str(lid))
os.system('mkdir /db/jobs/_' + str(lid) + '/input')
os.system('mkdir /db/jobs/_' + str(lid) + '/output')
os.system('chmod 777 /db/jobs/_' + str(lid) + '/output')
os.system('chmod 777 /db/jobs/_' + str(lid) + '/input')
#made config file
os.system('touch /db/jobs/_' + str(lid) + '/jobinfo.config')
os.system('chmod 777 /db/jobs/_' + str(lid) + '/jobinfo.config')
fjs = open('/db/jobs/_' + str(lid) + '/jobinfo.config', 'w')
fjs.write("name="+name+"\n")
fjs.write("input=inputfilepath"+"\n")
fjs.write("imgformat=png\n")
fjs.write("handshake="+hs+"\n")
fjs.write("jobid="+str(lid)+"\n")
fjs.close()
conn.commit()
"""
logfile.write("jobID " + jobid +" updated " + status + "\n")
conn.close()
logfile.close()

def sendMail(pname, receivers, jobid, url):
    initials = pname.split("@")[0]
    sender = 'jake.lin@uni.lu'
    #receivers.append("christian.jaeger@uni.lu")
    message = """From: IDARE Metanode Server <thomas.pfau@uni.lu>
To: User
Subject: %s

%s
    """ %(jobid + "_" + initials, "Hello " + pname + ",\n\nThe Metanode job you requested is completed and can be downloaded using the link below.\n" + url + "\n\nCheers and feel free to contact Thomas Pfau with questions.")

    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message)
    except SMTPException:
        print "Error: unable to send email"

#os.system('touch /var/www/metanodeui/data/_100.out')
#only send email when it is done/error, will script be called if not complete or error?

sendMail(name, [email, "jake.lin@student.tut.fi"], "Metanode status: " + status + " " + str(jobid), "http://idare-server.uni.lu/metanodeui/results.html?jobID=" + str(jobid) + "&handshake=" + handshake)



print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Jobid %s status %s</h2>
</body>
</html>
""" %(str(jobid), status)
